package com.dunjx.rabbitMq.work.lunxun;

import com.rabbitmq.client.*;
import lombok.SneakyThrows;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class c1 {

    public static Connection getConnection() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setHost("39.103.219.84");
        connectionFactory.setVirtualHost("/");
        return connectionFactory.newConnection("测试链接");
    }
    public static Runnable runnable = new Runnable() {
        @SneakyThrows
        @Override
        public void run() {
            Channel channel = null;
            Connection connection = getConnection();
            // 获取队列的名称
            try {
                // https://www.bilibili.com/video/BV1dX4y1V73G?p=26&spm_id_from=pageDriver
                String queueName = Thread.currentThread().getName();
                channel = connection.createChannel();
                // TODO false 手动应答  Qos 不设置 是轮训 每次从队列取多少条数据
                Channel finalChannel = channel;
                channel.basicQos(1);

                channel.basicConsume(queueName, false, new DeliverCallback() {
                    @SneakyThrows
                    @Override
                    public void handle(String consumerTag, Delivery message) throws IOException {
                        System.out.println(queueName+"接收的 = "+ new String(message.getBody(), "UTF-8"));
                        Thread.sleep(1000);
                        finalChannel.basicAck(message.getEnvelope().getDeliveryTag(),false);
                    }
                }, new CancelCallback() {
                    @Override
                    public void handle(String consumerTag) throws IOException {
                    }
                });
                System.out.println(queueName+":开始接受消息");
                System.in.read();
            } catch (IOException e) {
                System.out.println("接受消息异常");
                e.printStackTrace();
            } finally {
                if (channel != null && channel.isOpen()) {
                    channel.close();
                    System.out.println("通道关闭");
                }
                if (connection != null && connection.isOpen()) {
                    connection.close();
                    System.out.println("链接关闭");

                }

            }
        }
    };

    public static void main(String[] args) throws Exception {
        new Thread(runnable,"queue01").start();

    }
}
